/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.tompai.datagather.facebook;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.sql.Types;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.ws.http.HTTPException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.tompai.common.DataBaseUtils;
import com.tompai.common.time.TimeTransUtils;
import com.tompai.datagather.facebook.FacebookResponse.Data;
import com.tompai.datagather.facebook.FacebookResponse.Data.From;
import com.tompai.datagather.facebook.FacebookResponse.Data.Shares;
import com.tompai.datagather.model.NewsEntity;
import com.tompai.datagather.twitter.ShadowSockets5Proxy;

/**
 * @date 2016年8月22日 上午11:57:12
 * @version
 * @since JDK 1.8
 */
public class FacebookCrawler {

	public static final Logger LOG = LoggerFactory.getLogger(FacebookCrawler.class);

	/*
	 * VPS Socket5//
	 */
	public static FacebookResponse executeSearchVps(String url) {

		/*
		 * String ip = "127.0.0.1"; String sport="1080"; int port =
		 * Integer.parseInt(sport);
		 * 
		 * HttpClient client = new HttpClient();
		 * 
		 * client.getHostConfiguration().setProxy(ip, port);
		 * client.getParams().setAuthenticationPreemptive(true); GetMethod get = new
		 * GetMethod(url);
		 */

		String responseText = null;
		try {
			// client.executeMethod(get);
			responseText = ShadowSockets5Proxy.facebookLink(url);
		} catch (HTTPException e) {
			// TODO: handle exception
			LOG.error(e.getMessage());
		}

		Gson gson = new Gson();
		try {
			if (responseText != null) {
				return gson.fromJson(responseText, FacebookResponse.class);
			}
		} catch (JsonSyntaxException e) {
			// TODO: handle exception
			e.printStackTrace();
			try {
				throw new SocketTimeoutException();
			} catch (SocketTimeoutException e1) {
				// TODO Auto-generated catch block
				LOG.info(e1.getMessage());
			}
			return null;
		}
		return null;
	}

	// crawlerCount<=100
	public void saveFacebookAccount(String facebookAccount, int crawlerCount) {
		if (StringUtils.isEmpty(facebookAccount) || crawlerCount <= 0) {
			LOG.error("FacebookAccount is Null or theFacebook crawlerCount is less Zero!");
			return;
		}
		if (crawlerCount >= 100) {

			crawlerCount = 100;
		}
		String base = "https://graph.facebook.com/v2.6/";
		String fields = "id,created_time,from,link,message,picture,shares,type,updated_time";
		String count = String.valueOf(crawlerCount);
		String facebookapp_id = "";
		String facebookapp_secret = "";

		String access_token = facebookapp_id + "%7C" + facebookapp_secret;
		String pageUrl = base + facebookAccount + "/posts/?fields=" + fields + "&limit=" + count + "&access_token="
				+ access_token;
		FacebookResponse response = executeSearchVps(pageUrl);
		List<com.tompai.datagather.facebook.FacebookResponse.Data> datas = response.getData();
		if ((datas == null) || (datas.size() < 1)) {
			LOG.error("Get FaceBook Response data is Null!");
			return;
		}
		List<NewsEntity> entityList = new ArrayList<NewsEntity>();

		for (Data data : datas) {
			NewsEntity entity = new NewsEntity();
			if ((data.getId() != null) && (data.getId() != "")) {
				entity.setTwitterid(data.getId());
			} else {
				continue;
			}
			// String created_time = data.getCreated_time();//发表时间
			try {
				if ((data.getCreated_time() != null) && (data.getCreated_time() != "")) {
					if (data.getCreated_time() != null) {
						String formatType = "yyyy-MM-dd HH:mm:ss";
						entity.setPublishtime(TimeTransUtils.stringToDate(data.getCreated_time(), formatType));
					} else {
						continue;
					}
				} else {
					continue;
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
			if (data.getFrom() != null) {
				From from = data.getFrom();

				if ((from.getName() != null) && (from.getName() != "")) {
					entity.setAuthor(from.getName());
					entity.setKeyword(from.getName());
					String authorLink = "https://www.facebook.com/" + from.getName();
					entity.setAuthorlink(authorLink);
				} else {
					continue;
				}
				if ((from.getId() != null) && (from.getId() != "")) {
					// entity.TwitterUserId = from.getId();// 账号ID
					entity.setTwitterid(from.getId());
				} else {
					continue;
				}
			} else {
				continue;
			}

			// String link = data.getLink();//帖子链接
			if ((data.getLink() != null) && (data.getLink() != "")) {
				// entity.OriginalContent = data.getLink();
				entity.setOriginalcontent(data.getLink());
			} else {
				entity.setOriginalcontent("No Message Link");
			}
			if ((data.getMessage() != null) && (data.getMessage() != "")) {
				entity.setContent(data.getMessage());
				// entity.Content = ;
			} else {
				entity.setContent("No Message");
			}
			// String picture = data.getPicture();//图片链接
			if ((data.getPicture() != null) && (data.getPicture() != "")) {
				entity.setPicturelink(data.getPicture());
				entity.setHavepicture(true);
				// entity.HavePicture = true;
				// entity.PictureLink = ;
			}

			Shares shares = data.getShares();
			// Long sharesNumber = shares.getCount();//分享次数
			try {
				entity.setForwardnumber(new Long(shares.getCount()).intValue());
				;
				entity.setAttentiondegree(new Long(shares.getCount()).intValue());
			} catch (Exception e) {
				// entity.ForwardNumber = 0;
				// entity.AttentionDegree = 0;
			}

			// entity.ComeFrom = "Facebook";
			entity.setComefrom("Facebook");
			entity.setOriginalsource("Facebook");
			Date currentDate = new Date(System.currentTimeMillis());
			entity.setCollectiontime(currentDate);
			entityList.add(entity);
			// LOG.info(data.getCreated_time());
			// LOG.info(data.getMessage());
		}
		// 去重并入库
		// DataBaseUtils dataBaseUtils = new DataBaseUtils(baseDAO);
		// dataBaseUtils.saveFacebooks(entityList);
		LOG.info("Get FaceBook Account: [" + facebookAccount + " ] Texts Sucessfull.");
	}
	/*
	 * public void search(String[] facebookAccounts, int crawlerCount) {
	 * if(facebookAccounts.length==0){ LOG.error("The FacebookAccounts is Null .");
	 * return; } for(String account:facebookAccounts){ saveFacebookAccount(account,
	 * crawlerCount); } }
	 */
}